package study.算法Algorithm.常用10种算法.KMP算法;

/*
    暴力匹配算法 用来与KMP算法做比较
 */
public class ViolenceMatch {
    public static void main(String[] args) {
        //测试暴力匹配算法
        String str1 = "哈哈 嘿嘿  啊哈哈都撒砥砺奋进范德萨就";
        String str2 = "撒砥砺奋!";
        int i = violenceMatch(str1, str2);
        System.out.println("i = " + i);
    }

    //暴力匹配算法
    public static int violenceMatch(String str1, String str2) {
        char[] s1 = str1.toCharArray();
        char[] s2 = str2.toCharArray();

        int s1Len = s1.length;
        int s2Len = s2.length;

        int i = 0;  //i索引指向  s1
        int j = 0;  //j索引指向  s2
        while (i < s1Len && j < s2Len) {  //保证匹配时不会数组越界
            if (s1[i] == s2[j]) {    //匹配成功
                i++;
                j++;
            } else {
                i = i - (j - 1);
                j = 0;
            }
        }
        //判断是否匹配成功
        if (j == s2Len) {
            return i - j;
        }else {
            return  -1;
        }
    }
}
